/**
 * de.herberlin.sudoku.timer.Timesource
 */
package de.herberlin.sudoku.timer;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author herberlin
 * @created 17.06.2006
 */
public class Timesource extends TimerTask {

	private static Timesource _instance = null;

	public static Timesource getInstance() {
		if (_instance == null) {
			_instance = new Timesource();
			Timer timer = new Timer(true);
			timer.schedule(_instance, 500, 500);
		}
		return _instance;
	}

	public static void reset() {
		_instance=null;
	}

	public void run() {

		if (addThis.size()>0) {
			synchronized (addThis) {
				listenerList.addAll(addThis);
				addThis=new LinkedList();
			}
		}
		if (removeThis.size()>0) {
			synchronized(removeThis) {
				listenerList.removeAll(removeThis);
				removeThis=new LinkedList();
			}
		}

		Iterator it = listenerList.iterator();
		AnimationEvent event = new AnimationEvent(id);
		while (it.hasNext()) {
			((AnimationListener) it.next()).time(event);
		}
		id++;
	}

	private long id = 0L;

	private List listenerList = new LinkedList();
	private List addThis=new LinkedList();
	private List removeThis=new LinkedList();

	public synchronized void addListener(AnimationListener listener) {
		if (!addThis.contains(listener)) {
			addThis.add(listener);
		}
	}

	public synchronized void removeListener(AnimationListener listener) {
		removeThis.add(listener);
	}

}
